package com.hk.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

/**
 * ThreadLocal内存泄露问题演示及修复
 * @author: dpb
 * @date: 2022/11/24
 */
@RestController
@RequestMapping("/test")
public class ThreadLocalTestController {

    private static final ThreadLocal<Integer> currentUser = ThreadLocal.withInitial(() -> null);


    @GetMapping("wrong")
    public Map  wrong(@RequestParam("userId") Integer userId) {
        String before = Thread.currentThread().getName() + ":" + currentUser.get();
        currentUser.set(userId);
        String after = Thread.currentThread().getName() + ":" + currentUser.get();
        HashMap map = new HashMap();
        map.put("before", before);
        map.put("after", after);
        return map;
    }

    @GetMapping("right")
    public Map  right(@RequestParam("userId") Integer userId) {
        String before = Thread.currentThread().getName() + ":" + currentUser.get();
        currentUser.set(userId);
        try {

            String after = Thread.currentThread().getName() + ":" + currentUser.get();
            HashMap map = new HashMap();
            map.put("before", before);
            map.put("after", after);
            return map;
        } finally {
            currentUser.remove();
        }
    }


}
